package com.jiangsong.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

@Service
public class CommonService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private TransactionTemplate transactionTemplate;

    public void performTransaction() {
        transactionTemplate.execute((TransactionCallback<Integer>) status -> {
            try {
                jdbcTemplate.update("INSERT INTO your_table (column1, column2) VALUES (?,?)", "value1", "value2");
                jdbcTemplate.update("UPDATE your_table SET column2 =? WHERE column1 =?", "newValue2", "value1");
                return null;
            } catch (Exception e) {
                status.setRollbackOnly();
                throw e;
            }
        });
    }

    public void performTransaction1() {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {

                try {
                    jdbcTemplate.update("INSERT INTO your_table (column1, column2) VALUES (?,?)", "value1", "value2");
                    jdbcTemplate.update("UPDATE your_table SET column2 =? WHERE column1 =?", "newValue2", "value1");
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }
}